<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;

class VerifyCodeController extends ApiController
{

    public function store(Request $request, EasySms $easySms)
    {
        $captchaData = \Cache::get($request->captcha_key);

        if (!$captchaData) {
            return $this->failed('图片验证码已失效');
        }

        if (!hash_equals($captchaData['code'], $request->captcha_code)) {
            // 验证错误就清除缓存
            \Cache::forget($request->captcha_key);
            return $this->failed('验证码错误');
        }

        $phone = $captchaData['phone'];

        $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);

        try {
            $easySms->send($phone, [
                'content'  =>  "您的验证码是{$code}。如非本人操作，请忽略本短信",
                'template' => '',
                    'data' => [
                'code' => $code
            ]
            ]);
        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
            $message = $exception->getException('chuanglan')->getMessage();
            return $this->failed($message ?? '短信发送异常');
        }

        $key = 'verifyCode_'.str_random(15);
        $expiredAt = now()->addMinutes(10);
        // 缓存验证码 10分钟过期。
        \Cache::put($key, ['phone' => $phone, 'code' => $code], $expiredAt);
        // 清除图片验证码缓存
        \Cache::forget($request->captcha_key);

        return $this->success([
            'key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
        ]);
    }

    public function checkSmsCode(Request $request)
    {
        $verifyData = $this->cacheGet($request->sms_key);

        if (!$verifyData) {
            return $this->failed('验证码已失效', 422);
        }
        if (!hash_equals(strval($verifyData['sms_code']), $request->sms_code)) return $this->failed('验证码不正确');
        return $this->success('验证通过');
    }
}
